package model

import (
	"github.com/gofrs/uuid"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

type SysUser struct {
	BaseModel // ID 创建时间 更新时间 删除时间
	UUID        uuid.UUID `json:"uuid" gorm:"column:uuid;comment:用户UUID"`
	Name        string  `json:"name" gorm:"varchar(20);not null"`         // 用户名
	Nick        string  `json:"nick" gorm:"varchar(20);not null"`                            // 昵称
	Password    string  `json:"password,omitempty" gorm:"size:255;not null"`                 // Hash密码
	Avatar      string  `json:"avatar"`                                                      // 头像uri
	Description string  `json:"desc" gorm:"size:255"`                                        // 用户介绍
	RoleID      uint    `json:"roleId" gorm:"not null;index;default:2"`                      // 角色ID
	Role        SysRole `json:"role";gorm:"foreignkey:RoleID;AssociationForeignKey:RoleID"` //指定关联外键
	//RoleName 	string `json:"roleName"`
}

type SysUserLogin struct {
	Name     string `json:"name" binding:"required"`
	Password string `json:"password" binding:"required"`
}

// BeforeCreate 钩子，保存哈希密码
func (u *SysUser) BeforeCreate(tx *gorm.DB) (err error) {
	UUID, err := uuid.NewV4()
	if err != nil{
		panic("implement me")
	} else {
		u.UUID = UUID
	}
	//fmt.Printf("%v\n", u.UUID)
	hashPassword, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
	if err != nil {
		//response.Response(c, http.StatusInternalServerError, 500, "加密错误", nil)
		return err
	}
	u.Password = string(hashPassword)

	if u.Avatar == "" {
		u.Avatar = "https://api.multiavatar.com/"+u.UUID.String()+".svg"
	}

	return nil
}
